package de.barny.worm;

import java.awt.Color;
import java.awt.Graphics;
import java.util.LinkedList;
import java.util.List;

import de.barny.prefs.Var;

public class Snake {

	public List<Dot> dots = new LinkedList<Dot>();

	char dir;
	char oldDir;

	int playerN;
	
	Color dotColor;

	public Snake(int d, int player) {
		playerN = player;
		
		if (playerN == 1) {
			dotColor = new Color(120,150,255);
		} else if (playerN == 2) {
			dotColor = new Color(120,255,150);
		}
		initSnake(d);
	}

	public Snake(int d) {
		initSnake(d);
	}

	public void initSnake(int n) {
		dots.clear();

		if (playerN == 1) {
			dir = 'r';
			oldDir = 'r';

			for (int i = 1; i <= n; i++) {
				dots.add(new Dot(i, 2, dotColor));
			}
		} else if (playerN == 2) {
			dir = 'l';
			oldDir = 'l';

			int windowWidth = Var.windowWidth;
			int windowHeight = Var.windowHeight;
			int dotSize = Var.snakeDotSize;

			int possibilitiesX = windowWidth/dotSize;
			int possibilitiesY = windowHeight/dotSize;

			for (int i = 1; i <= n; i++) {
				dots.add(new Dot(possibilitiesX-i, possibilitiesY-2, dotColor));
			}
		}
	}

	public void paint(Graphics gameFieldGraphics) {
		Dot lastDot = getLastDot();
		
		if (dir == 'r' && oldDir != 'l') {
			dots.remove(0);
			dots.add(new Dot(lastDot.getPosX()+1, lastDot.getPosY(), dotColor));
			setOldDirection();
		} else if (dir == 'l' && oldDir != 'r') {
			dots.remove(0);
			dots.add(new Dot(lastDot.getPosX()-1, lastDot.getPosY(), dotColor));
			setOldDirection();
		} else if (dir == 'u' && oldDir != 'd') {
			dots.remove(0);
			dots.add(new Dot(lastDot.getPosX(), lastDot.getPosY()-1, dotColor));
			setOldDirection();
		} else if (dir == 'd' && oldDir != 'u') {
			dots.remove(0);
			dots.add(new Dot(lastDot.getPosX(), lastDot.getPosY()+1, dotColor));
			setOldDirection();
		} else {
			if (oldDir == 'r') {
				dots.remove(0);
				dots.add(new Dot(lastDot.getPosX()+1, lastDot.getPosY(), dotColor));
			} else if (oldDir == 'l') {
				dots.remove(0);
				dots.add(new Dot(lastDot.getPosX()-1, lastDot.getPosY(), dotColor));
			} else if (oldDir == 'u') {
				dots.remove(0);
				dots.add(new Dot(lastDot.getPosX(), lastDot.getPosY()-1, dotColor));
			} else if (oldDir == 'd') {
				dots.remove(0);
				dots.add(new Dot(lastDot.getPosX(), lastDot.getPosY()+1, dotColor));
			}
		}

		for (Dot dot: dots) {
			dot.setDotsListSize(dots);
			dot.paint(gameFieldGraphics);
		}
	}

	public void addDot() {
		for (int i = 0; i < Var.appleCarbonhydrates; i++) {
			dots.add(0, new Dot(0, 0, dotColor)); //Der Dot wird hier auf (0, 0) gesetzt, da er sowieso gleich wieder entfernt wird.
		}
	}

	public void setDirection(char d) {
		dir = d;
	}
	
	public void setOldDirection() {
		oldDir = dir;
	}
	
	public char getDirection() {
		return dir;
	}

	public Dot getLastDot() {
		return dots.get(dots.size()-1);
	}

}
